package com.gitee.feizns.quickstart.validation;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 验证工具类
 * @author feizns
 * @since 2023/2/12
 */
public class ValidationUtils {


    /**
     * 验证器
     * @see Validator
     */
    private static Validator VALIDATOR;
    static {
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            VALIDATOR = factory.getValidator();
        }
    }

    /**
     * 设置数据校验器
     * <p>
     *     对于有环境要求的可以通过改方法来设置配置过的验证器
     * </p>
     * @param validator {@link Validator}
     */
    public static void setValidator(Validator validator) {
        VALIDATOR = validator;
    }

    /**
     * 验证
     * @see Validator#validate(Object, Class[])
     * @param bean 验证的bean
     * @param groups {@link Validator#validate(Object, Class[])}
     * @return {@link ConstraintViolation}
     */
    public static Set<ConstraintViolation<Object>> validate(Object bean, Class<?>... groups) {
        return VALIDATOR.validate(bean, groups);
    }

    /**
     * 验证（如果有异常则抛出）
     * @see Validator#validate(Object, Class[])
     * @param bean 验证的bean
     * @param groups {@link Validator#validate(Object, Class[])}
     */
    public static void validateIfFailsThenThrow(Object bean, Class<?>... groups) {
        Set<ConstraintViolation<Object>> validate = validate(bean, groups);
        if ( !validate.isEmpty() )
            throw new ConstraintViolationException(validate);
    }

}
